package com.pzhu.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.pzhu.pojo.User;
import com.pzhu.service.LoginService;
import com.pzhu.service.impl.LoginServiceImpl;

public class LoginServlet extends HttpServlet {
	//创建业务层对象
	LoginService ls=new LoginServiceImpl();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;charset=utf-8");
		//获取用户请求数据
		String uname=req.getParameter("uname");
		String pwd=req.getParameter("pwd");
		//处理请求信息
		//获取业务层对象
		User u=ls.checkLoginService(uname, pwd);
		//响应处理结果
		if(u!=null){
			System.out.println(uname+"登陆成功");
			//创建用户登陆的cookie对象
			Cookie c=new Cookie("uid",u.getUid()+"");
			//设置cookie有效期
			c.setMaxAge(3*24*3600);
			//设置有效路径，指定与Cookie相关的Servlet
			c.setPath("/ss/ckl");
			//向浏览器添加cookie
			resp.addCookie(c);
			//创建Session对象实例
			HttpSession hs=req.getSession();
			//添加Session数据，键名user，键值是u对象
			hs.setAttribute("user", u);
			//登录成功，重定向到main
			resp.sendRedirect("/se/main");
			//重定向用return结束
			return;
		}else{
			System.out.println(uname+"登陆失败");
			//添加用户数据，用于登录失败的提示语
			req.setAttribute("str", uname+"登录失败");
			//登录失败，请求转发到page
			req.getRequestDispatcher("/page").forward(req, resp);
			//请求转发用return结束
			return;
		}
	}

}
